using System.Reflection;
using AutoMapper;
using AutoMapper.Internal;
using ZeroSum.Extend.Mapper.Annotations;
using ZeroSum.Extensions;

namespace ZeroSum.Extend.Mapper.Extensions;

/// <summary>
///     Assembly扩展类（AutoMapper专用）
/// </summary>
internal static class AssemblyExtensions
{
    /// <summary>
    ///     获取所有实现了ITypeConvert的类
    /// </summary>
    /// <param name="assemblies"></param>
    /// <returns></returns>
    internal static IEnumerable<ConvertType> GetConverterTypes(this Assembly[] assemblies)
    {
        var allTypes = assemblies.SelectMany(t => t.GetTypes());
        var targetType = typeof(ITypeConverter<,>);
        return allTypes.Where(t => t.IsImplGenericInterface(targetType)).Select(x =>
        {
            var genericArgs = x.GetGenericInterface(targetType).GetGenericArguments();
            return new ConvertType
            {
                SourceType = genericArgs[0],
                DestinationType = genericArgs[1],
                Converter = x
            };
        });
    }

    internal static IEnumerable<Type> GetMapToTypes(this Assembly[] assemblies)
    {
        var allTypes = assemblies.SelectMany(t => t.GetTypes());
        return allTypes.Where(t => t.CanInstanced())
            .Where(t => t.HasAttribute<AutoMapToAttribute>());
    }
}

/// <summary>
///     实现了ITypeConvert的类，存储泛型参数
/// </summary>
internal class ConvertType
{
    public Type? SourceType { get; set; }
    public Type? DestinationType { get; set; }
    public Type? Converter { get; set; }
}